package com.matt.components.intercepter;


import com.matt.domain.ActionLog;
import com.matt.foundation.utils.IpHelper;
import com.matt.foundation.utils.ModelUtil;
import com.matt.repository.ActionLogRepository;
import com.matt.remoteCall.SsoCallService;
import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.matt.commons.constant.CommonConstant.AUTH_VALUE;


/**
 * *******************************
 * Created by Ron.
 * form com.matt
 * on 2017/5/18
 * *******************************
 */
@Slf4j
public class ActionLogInterceptor implements HandlerInterceptor {

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private ActionLogRepository teachActionLogRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ip = IpHelper.getRequestIpAddr(request);
        String params = ModelUtil.objectMapper.writeValueAsString(request.getParameterMap());

        String requestUrl = request.getRequestURI();
        String staffId = "";
        String ticket = "";
        String ht = request.getHeader("ticket");

        if (request.getHeader("ticket") != null && StringUtils.isNotBlank(request.getHeader("ticket")) && !AUTH_VALUE.equals(request.getHeader("ticket"))) {
            ticket = ht;
            staffId = ssoCallService.getStaffDTO(ticket).getId();
        }
        log.info("request ticket:[{}], staffId:[{}], URL:[{}] ,params:[{}], request ip :[{}]", ticket, staffId, requestUrl, params, ip);

        ActionLog log = ActionLog.of(staffId, requestUrl, params, ip);
        teachActionLogRepository.save(log);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
